package zld369504.tw.m_team;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;

import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.Response;
import zld369504.tw.m_team.api.MTeamHttpsApi;
import zld369504.tw.m_team.api.MTeamHttpsApiImpl;

public class LauncherActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
        DatabaseHelper db = DatabaseHelper.getHelper(this);

        Flowable.create(new FlowableOnSubscribe<String>() {
            @Override
            public void subscribe(final FlowableEmitter<String> emitter) throws Exception {
                List<LocalCookieStore> list = DatabaseHelper.getHelper(LauncherActivity.this).getCookieDao().queryForAll();
                if (list != null && list.size() > 0) {
                    final MTeamHttpsApi api = MTeamHttpsApiImpl.getInstance();
                    Response response=api.getMainPage();
                    int responseCode = response.code();
                    if (responseCode == 302) {
                        Headers headers = response.headers();
                        List<String> valueList = headers.values("Location");
                        boolean redirectToLogin = false;
                        boolean redirectToVerify = false;
                        String verifyUrl=null;
                        for (String s : valueList) {
                            if (s.contains("login.php")) {
                                redirectToLogin = true;
                                break;
                            } else if (s.contains("verify.php")) {
                                verifyUrl=s;
                                redirectToVerify = true;
                                break;
                            }
                        }
                        if (redirectToLogin) {
                            LauncherException ex = new LauncherException("");
                            ex.code = LauncherException.CODE_REDIRECT_TO_LOGIN;
                            emitter.onError(ex);
                        }
                        if (redirectToVerify) {
                            Response realResponse=api.verify(verifyUrl);
                            if(realResponse!=null){
                                if (realResponse.code() == 200) {
                                    String body = realResponse.body().string();
                                    emitter.onNext(body);
                                    emitter.onComplete();
                                } else {
                                    //验证后按照跳转过去获得的code不是200
                                    LauncherException ex1=new LauncherException("");
                                    ex1.code=LauncherException.CODE_VERIFY_RESULT_FAILED;
                                    emitter.onError(ex1);
                                }
                            } else {
                                //验证网页返回不是302code
                                LauncherException ex = new LauncherException("");
                                ex.code = LauncherException.CODE_VERIFY_FAILED;
                                emitter.onError(ex);
                            }
                        }
                    } else if (responseCode == 200) {
                        emitter.onNext(response.body().string());
                        emitter.onComplete();
                    } else {
                        LauncherException ex = new LauncherException("code=" + responseCode);
                        ex.code = LauncherException.CODE_OTHER_RESPONSE_CODE;
                        emitter.onError(ex);
                    }
                } else {
                    LauncherException ex = new LauncherException("");
                    ex.code = LauncherException.CODE_NO_COOKIE;
                    emitter.onError(ex);
                }
            }
        }, BackpressureStrategy.DROP)
                .map(new Function<String, Boolean>() {
                    @Override
                    public Boolean apply(String s) throws Exception {
                        return DataParser.parseUserBriefInfoFromMainPageSide(s);
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onSubscribe(Subscription s) {
                        s.request(1);
                    }

                    @Override
                    public void onNext(Boolean aVoid) {
                        if(aVoid){
                            Intent intent = new Intent(LauncherActivity.this, MainActivity.class);
                            intent.putExtra("needLoadIndexPage", false);
                            startActivity(intent);
                        } else {
                            startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                        }
                        finish();
                    }

                    @Override
                    public void onError(Throwable t) {
                        if (t instanceof SQLException) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                                            finish();
                                        }
                                    });
                                }
                            }, 2000);
                        } else if (t instanceof LauncherException) {
                            //自定义的错误
                            LauncherException ex = (LauncherException) t;
                            switch (ex.code) {
                                case LauncherException.CODE_NO_COOKIE:
                                    new Handler().postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                                                    finish();
                                                }
                                            });
                                        }
                                    }, 2000);
                                    break;
                                case LauncherException.CODE_OTHER_RESPONSE_CODE:
                                    showErrorDialog(ex.message);
                                    break;
                                case LauncherException.CODE_REDIRECT_TO_LOGIN:
                                case LauncherException.CODE_VERIFY_FAILED:
                                case LauncherException.CODE_VERIFY_RESULT_FAILED:
                                    startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                                    finish();
                                    break;
                            }
                        } else {
                            t.printStackTrace();
                            startActivity(new Intent(LauncherActivity.this, LoginActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    class LauncherException extends Exception {

        static final int CODE_NO_COOKIE = -1;
        static final int CODE_REDIRECT_TO_LOGIN = 1;
        static final int CODE_OTHER_RESPONSE_CODE = 2;
        static final int CODE_VERIFY_RESULT_FAILED = 3;
        static final int CODE_VERIFY_FAILED = 4;

        private int code;
        private String message;

        LauncherException(String message) {
            super(message);
            this.message=message;
        }
    }


}
